//
//  VCAssetChosedViewController.m
//  VideoCollage
//
//  Created by Mac on 2018/6/25.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "VCAssetChosedViewController.h"
#import "STSegementAutoView.h"
#import "VCAllViewController.h"
#import "VCPhotoViewController.h"
#import "VCVideoViewController.h"
@interface VCAssetChosedViewController ()<PHPhotoLibraryChangeObserver>
@property(nonatomic, strong) STSegementAutoView                     *autoView;/**< 头部单选按钮 */
@end

@implementation VCAssetChosedViewController
+ (VCAssetChosedViewController *)defult{
    static VCAssetChosedViewController * defult = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defult = VCAssetChosedViewController.new;
         [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:defult];
    });
    return defult;
}
#pragma mark --- PHPhotoLibraryChangeObserver
- (void)photoLibraryDidChange:(PHChange *)changeInstance{
    //监听相册是否改变，改变则更新数据
    self.shouldUpDateAllModel = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (!self.selectedModels) {
        self.selectedModels = NSMutableArray.new;
    }
    self.selectedAssetIds = NSMutableArray.new;
    [self configSubView];
    self.itemView.assetModles = self.selectedModels;
    [self addNotifacations];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.shouldUpDateAllModel) {
        self.shouldUpDateAllModel = NO;
        [self repeatRequestFormPhoto];//重新请求数据
        self.itemView.assetModles = self.selectedModels;
        
    }else{
        if (!self.selectedModels) {
            self.selectedModels = NSMutableArray.new;
        }
        [self configItemView];
        self.itemView.assetModles = self.selectedModels;
        [self reloadAllData];
    }
    
}
- (void)forceFindVideoImage:(NSString *)videoId handle:(void (^)(TZAssetModel *))handle{

   __block TZAssetModel * finshModel = nil;
        [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:NO needFetchAssets:NO completion:^(TZAlbumModel *model) {
            [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:YES allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                
                if (models.count) {
                    for (TZAssetModel * assetModel in models) {
                        PHAsset * asset = assetModel.asset;
                        if ([asset.localIdentifier isEqualToString:videoId]) {
                            finshModel = assetModel;
                            break;
                        }
                    }
                    
                }
                if (handle) {
                    handle(finshModel);
                }
            }];
        }];

    

}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onReciveModelSelctedNotify:)
                                                 name:modelSelctedNotifation
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onReciveModelUnSelctedNotify:)
                                                 name:modelUnSelctedNotifation
                                               object:nil];
    
}
- (void)onReciveModelSelctedNotify:(NSNotification*)notify{
    VCItemEditViewController * vc = self.navigationController.childViewControllers[1];
    vc.selectedModels = self.selectedModels;
    self.itemView.assetModles = self.selectedModels;
}
- (void)onReciveModelUnSelctedNotify:(NSNotification*)notify{
    self.itemView.assetModles = self.selectedModels;
    VCItemEditViewController * vc = self.navigationController.childViewControllers[1];
    vc.selectedModels = self.selectedModels;
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.view.backgroundColor = TM_backgroundColor;
    STSegementAutoView * view = [[STSegementAutoView alloc] initWithFrame:CGRectMake(0, 0, 0.6 * UIScreenWidth, 30) andTitle:@[@"All",@"Photo",@"Video"] handle:^(STSegementAutoView *sender, UIButton *currentSelctedButton) {
        if (sender.cureentIndex == 0) {
            VCAllViewController * vc = (id)weakSelf.childViewControllers.firstObject;
            [vc.collectionView reloadData];
        }
        if (sender.cureentIndex == 1) {
            VCPhotoViewController * vc = (id)weakSelf.childViewControllers[1];
            [vc.collectionView reloadData];
        }
        if (sender.cureentIndex == 2) {
            VCVideoViewController * vc = (id)weakSelf.childViewControllers[2];
            [vc.collectionView reloadData];
        }
        [weakSelf.scrollView setContentOffset:CGPointMake(UIScreenWidth * sender.cureentIndex, 0) animated:YES];
    }];
    view.lineSelectedColor = UIColor.clearColor;
    view.lineColor = UIColor.clearColor;
    view.butTitleColor = SecendTextColor;
    view.butTitleSelectedColor = TM_redColor;
    self.navigationItem.titleView = view;
    self.autoView = view;
    [self configItemView];
    CGFloat itemWith = UIScreenWidth / 2;
    CGRect finshFrame = CGRectMake(itemWith/2, TMUtils.navgationBarBootom + 20, itemWith, itemWith);
    UIView *tempView = [[UIView alloc] initWithFrame:finshFrame];
    
    self.scrollView.backgroundColor = UIColor.whiteColor;
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, tempView.bottom + 20, UIScreenWidth, TMUtils.tabBarTop + 49 - (self.itemView.bottom + 20))];
    self.scrollView.backgroundColor = UIColor.whiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.scrollView];
    if (ios11 && [self.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.scrollView setContentInsetAdjustmentBehavior:@(2)];
    }
    
    VCAllViewController * vc1 = VCAllViewController.new;
    [self addChildViewController:vc1];
    vc1.view.left = 0;
    [self.scrollView addSubview:vc1.view];
    
    VCPhotoViewController * vc2 = VCPhotoViewController.new;
    [self addChildViewController:vc2];
    vc2.view.left = UIScreenWidth;
    [self.scrollView addSubview:vc2.view];
    
    VCVideoViewController * vc3 = VCVideoViewController.new;
    [self addChildViewController:vc3];
    vc3.view.left = 2 * UIScreenWidth;
    [self.scrollView addSubview:vc3.view];
    [SVProgressHUD showWithStatus:@"Loading"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:YES needFetchAssets:NO completion:^(TZAlbumModel *model) {
            [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:YES allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
               
                if (models.count) {
                    self.allModels = models;
                    NSMutableArray * videoArray = NSMutableArray.new;
                    NSMutableArray * photoArray = NSMutableArray.new;
                    for (TZAssetModel * assetModel in models) {
                        //判断是否在selcted 中
                        PHAsset * asset = assetModel.asset;
                        assetModel.assetID = asset.localIdentifier;
                        BOOL selcted = [self isSlectedFormModel:assetModel];
                        assetModel.isSelected = selcted;
                        if (assetModel.type == TZAssetModelMediaTypePhoto) {
                            [photoArray addObject:assetModel];
                        }
                        if (assetModel.type == TZAssetModelMediaTypeVideo) {
                            [videoArray addObject:assetModel];
                        }
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                         [SVProgressHUD dismiss];
                        vc1.assetsArray = models;
                        vc2.assetsArray = photoArray;
                        vc3.assetsArray = videoArray;
                        self.allModels = models;
                        self.photoModels = photoArray;
                        self.videoModels = videoArray;
                        
                    });
                    
                }
            }];
        }];
    });
    self.scrollView.contentSize = CGSizeMake(self.childViewControllers.count * UIScreenWidth, 0);
    self.scrollView.pagingEnabled = YES;
    [self.view addSubview:self.scrollView];

}
- (void)configItemView{
    self.itemView = [[VCItemView alloc] initWithRank:self.rank];
    self.itemView.top = TMUtils.navgationBarBootom + 47;
    self.itemView.layer.cornerRadius = 4;
    self.itemView.clipsToBounds = YES;
    self.itemView.maxWith = 0.5 * UIScreenWidth;
    [self.view addSubview:self.itemView];
    CGFloat itemWith = UIScreenWidth / 2;
    CGRect finshFrame = CGRectMake(itemWith/2, TMUtils.navgationBarBootom + 20, itemWith, itemWith);
    self.itemView.frame = finshFrame;
    self.itemView.layer.shadowOffset = CGSizeMake(0, 0);
    self.itemView.layer.shadowColor = TM_redColor.CGColor;
    self.itemView.layer.shadowRadius = 1;
    self.itemView.layer.shadowOpacity = .5f;
    CGRect shadowFrame = CGRectMake(self.itemView.left - 1, self.itemView.top - 1, self.itemView.width + 1, self.itemView.height + 1);
    CGPathRef shadowPath = [UIBezierPath
                            bezierPathWithRect:shadowFrame].CGPath;
    self.itemView.layer.shadowPath = shadowPath;
    [self.itemView updateItemFrame];
    for (UIImageView * imageView in self.itemView.itemImageViewArray) {
        imageView.hidden = NO;
        [imageView setImage:DefultAddImage];
    }
}
#pragma mark --Private Method
- (void)reloadAllData{
    NSMutableArray * videoArray = NSMutableArray.new;
    NSMutableArray * photoArray = NSMutableArray.new;
    
    for (TZAssetModel * assetModel in self.allModels) {
        //判断是否在selcted 中
        PHAsset * asset = assetModel.asset;
        assetModel.assetID = asset.localIdentifier;
        BOOL selcted = [self isSlectedFormModel:assetModel];
        assetModel.isSelected = selcted;
        if (assetModel.type == TZAssetModelMediaTypePhoto) {
            [photoArray addObject:assetModel];
        }
        if (assetModel.type == TZAssetModelMediaTypeVideo) {
            [videoArray addObject:assetModel];
        }
    }
    
    VCAllViewController * vc1 = self.childViewControllers.firstObject;
    VCPhotoViewController * vc2 = self.childViewControllers[1];
    VCVideoViewController * vc3 = self.childViewControllers.lastObject;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        vc1.assetsArray = self.allModels;
        vc2.assetsArray = photoArray;
        vc3.assetsArray = videoArray;
        self.photoModels = photoArray;
        self.videoModels = videoArray;
    });
}
- (void)repeatRequestFormPhoto{
    VCAllViewController * vc1 = self.childViewControllers.firstObject;
    VCPhotoViewController * vc2 = self.childViewControllers[1];
    VCVideoViewController * vc3 = self.childViewControllers.lastObject;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [SVProgressHUD showWithStatus:@"Loading"];
        [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:YES needFetchAssets:NO completion:^(TZAlbumModel *model) {
            [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:YES allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                
                if (models.count) {
                    self.allModels = models;
                    NSMutableArray * videoArray = NSMutableArray.new;
                    NSMutableArray * photoArray = NSMutableArray.new;
                    for (TZAssetModel * assetModel in models) {                        
                        //判断是否在selcted 中
                        PHAsset * asset = assetModel.asset;
                        assetModel.assetID = asset.localIdentifier;
                        BOOL selcted = [self isSlectedFormModel:assetModel];
                        assetModel.isSelected = selcted;
                        if (assetModel.type == TZAssetModelMediaTypePhoto) {
                            [photoArray addObject:assetModel];
                        }
                        if (assetModel.type == TZAssetModelMediaTypeVideo) {
                            [videoArray addObject:assetModel];
                        }
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        vc1.assetsArray = models;
                        vc2.assetsArray = photoArray;
                        vc3.assetsArray = videoArray;
                        self.allModels = models;
                        self.photoModels = photoArray;
                        self.videoModels = videoArray;
                        [SVProgressHUD dismiss];
                    });
                    
                }
            }];
        }];
    });
}
- (void)addSelectedModel:(TZAssetModel *)model {
    [_selectedModels addObject:model];
}
- (void)removeSelectedModel:(TZAssetModel *)model {
    [_selectedModels removeObject:model];
    NSString *assetId = [[TZImageManager manager] getAssetIdentifier:model.asset];
    [_selectedAssetIds removeObject:assetId];
}
- (BOOL)isSlectedFormModel:(TZAssetModel*)currentModel{
    BOOL existModel = NO;
    for (TZAssetModel * model in self.selectedModels) {
        if ([currentModel.assetID isEqualToString:model.assetID]) {
            existModel = YES;
        }
    }
    return existModel;
}
@end

